package com.spotalog.server.service.search;

import java.util.Date;
import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.spotalog.shared.model.Location;

/**
 * Created with IntelliJ IDEA. User: seandoyle Date: 8/10/12 Time: 12:25 PM To
 * change this template use File | Settings | File Templates.
 */
public final class Queries {
	private static final Joiner OR = Joiner.on(" OR ");
	private static final Joiner AND = Joiner.on(" AND ");

	private Queries() {}

	public static String or(Iterable<? extends String> terms) {
		return OR.join(terms);
	}

	public static String and(Iterable<? extends String> terms) {
		return AND.join(terms);
	}

	public static String before(String fieldName, Date date) {
		return String.format("%s < %s", fieldName, date);
	}

	public static String after(String fieldName, Date date) {
		return String.format("%s > %s", fieldName, date);
	}

	public static String distance(String fieldName, Location to) {
		return String.format("distance(geopoint(%f,%f),%s)", to.getLatitude(), to.getLongitude(),
				fieldName);
	}

	public static String distance(String fieldName, Location to, double maxDistance) {
		return String.format("%s < %f", distance(fieldName, to), maxDistance);
	}

	public static String type(String fieldName, Enum<?> value) {
		return String.format("%s:%s", fieldName, value);
	}

	public static String keywords(String phrase, String field, String... fields) {
		List<String> query = Lists.newArrayList();
		query.add(String.format("%s:\"%s\"", field, phrase));
		for (String otherField : fields) {
			query.add(String.format("%s:\"%s\"", otherField, phrase));
		}
		return OR.join(query);
	}
}
